<?php
include("../../../../common.php");
pe_lead('hook/wechat.hook.php');
switch ($act) {
	//####################// 获取opoenid //####################//
	case 'login':
		$json = pe_curl_get("https://api.weixin.qq.com/sns/jscode2session?appid={$cache_setting['minapp_appid']}&secret={$cache_setting['minapp_appsecret']}&js_code={$_g_code}&grant_type=authorization_code");
		$json = json_decode($json, true);
		$user_openid = pe_dbhold($json['openid']);
		$user_unionid = pe_dbhold($json['unionid']);
		if (!$user_openid) pe_apidata(array('code'=>0, 'msg'=>"{$json['errcode']}：{$json['errmsg']}"));
		if ($user_unionid) {
			$openid = $db->pe_select('user_openid', array('user_wx_unionid'=>$user_unionid));
		} 
		if (!$openid['user_id']) {
			$openid = $db->pe_select('user_openid', array('user_minapp_openid'=>$user_openid));
		}		
		if ($openid['user_id']) {
			user_login_callback('login', $openid['user_id']);	
		}
		$info['user_id'] = intval($openid['user_id']);
		$info['user_openid'] = $user_openid;
		$info['user_unionid'] = $user_unionid;
		$info['session_key'] = $json['session_key'];
		pe_apidata(array('code'=>1, 'data'=>$info));
	break;
	//####################// 获取access_token //####################//
	case 'access_token':
		$wechat_config = wechat_config();
		echo $wechat_config['minapp_access_token'];
	break;
	//####################// 获取用户昵称+头像 //####################//
	case 'get_userinfo':
		$json = json_decode(str_ireplace(' ', '+', urldecode($_g_data)), true);
		if ($json['nickName']) {
			$login3['user_name'] = $json['nickName'];
			$login3['user_logo'] = $json['avatarUrl'];
			$login3['user_minapp_openid'] = $_g_user_openid;
			$login3['user_wx_unionid'] = $_g_user_unionid;
			$login3['from'] = 'wx';
			pe_set_session('login3', $login3);
			pe_apidata(array('code'=>1));
		}
		else {
			pe_apidata($json);
		}
	break;
	//####################// 获取手机号并自动注册帐号 //####################//
	case 'get_userphone':
		$data = str_ireplace(' ', '+', urldecode($_g_data));
		$iv = str_ireplace(' ', '+', urldecode($_g_iv));
		$session_key = str_ireplace(' ', '+', urldecode($_g_session_key));
		$json = minapp_data_jiemi($data, $iv, $session_key);
		if ($json['code']) {
			$login3 = pe_get_session('login3');
			$login3 = is_array($login3) ? $login3 : array();
			$login3['user_phone'] = pe_dbhold($json['data']['purePhoneNumber']);
			pe_set_session('login3', $login3);
			pe_apidata(array('code'=>1));
		}
		else {
			pe_apidata($json);		
		}
	break;
}
?>